<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>在线支付</p>
    </header>

    <!-- 订单信息部分 -->
    <h3>订单信息：</h3>
    <div class="order-info" v-if="orders && orders.business">
      <p>
        {{ orders.business.businessName }}
        <i class="fa fa-caret-down" @click="detailetShow"></i>
      </p>
      <p>&#165;{{ finalTotal }}</p> <!-- 更新后的订单总额 -->
    </div>
    <div v-else>
      <p>订单信息加载中...</p>
    </div>

    <!-- 订单明细部分 -->
    <ul class="order-detailet" v-show="isShowDetailet" v-if="orders && orders.list">
      <li v-for="item in orders.list" :key="item.food.foodId">
        <p>{{ item.food.foodName }} x {{ item.quantity }}</p>
        <p>&#165;{{ item.food.foodPrice * item.quantity }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&#165;{{ orders.business.deliveryPrice }}</p>
      </li>
      <li>
        <p>积分优惠</p>
        <p>-&#165;{{ usedScoreAmount }}</p> <!-- 这里显示积分抵扣的金额 -->
      </li>
    </ul>

    <!-- 可用积分部分 -->
    <div class="available-score">
      <label>可用积分: {{ availableScore }}</label>
      <input
          type="number"
          v-model="usedScore"
          @input="handleScoreInput"
          :max="availableScore"
          :min="0"
          style="width: 100px;"
      />
    </div>

    <!-- 支付方式部分 -->
    <ul class="payment-type">
      <li>
        <img src="../assets/alipay.png" />
        <i class="fa fa-check-circle"></i>
      </li>
      <li>
        <img src="../assets/wechat.png" />
      </li>
    </ul>

    <!-- 支付按钮 -->
    <div class="payment-button">
      <button @click="toIndex">确认支付</button>
    </div>

    <!-- 底部菜单部分 -->
    <Footer />
  </div>
</template>

<script>
import Footer from "../components/Footer.vue";
import axios from 'axios';
import qs from 'qs';

export default {
  name: "Payment",
  data() {
    return {
      orderId: this.$route.query.orderId,
      availableScore: 0,  // 可用积分
      usedScore: 0,       // 用户使用的积分
      usedScoreAmount: 0, // 积分抵扣的金额
      finalTotal: 0,      // 最终需要支付的金额
      orders: {
        business: {}, // 确保 orders 对象有 business 属性
        list: [], // 确保 orders 对象有 list 属性来保存订单明细
      },
      isShowDetailet: false, // 是否显示明细
    };
  },
  created() {
    this.orderId = this.$route.query.orderId;

    // 确认订单 ID 是否正确传递
    if (!this.orderId) {
      alert('订单 ID 不存在');
      return;
    }

    // 请求订单信息
    this.$axios.post('OrdersController/getOrdersById', this.$qs.stringify({
      orderId: this.orderId
    }))
        .then(response => {
          this.orders = response.data;
          if (this.orders && this.orders.business && this.orders.list) {
            this.calculateFinalTotal();
          } else {
            console.error("订单信息缺失");
          }
        })
        .catch(error => {
          console.error('获取订单失败:', error);
        });

    // 确保 userId 被正确传递
    const userId = this.$route.query.userId;
    if (!userId) {
      console.error("缺少 userId 参数");
      return;
    }

    // 请求用户的可用积分
    this.$axios.post('/ScoreController/getAllScore', qs.stringify({
      userId: userId
    }))
        .then(response => {
          this.availableScore = response.data;  // 设置可用积分
        })
        .catch(error => {
          console.error("获取可用积分失败:", error);
        });
  },
  methods: {
    detailetShow() {
      this.isShowDetailet = !this.isShowDetailet;
    },
    handleScoreInput() {
      // 限制用户输入的积分不能超过可用积分
      if (this.usedScore > this.availableScore) {
        this.usedScore = this.availableScore;
      }

      // 按照 10 积分 = 1 元计算抵扣金额
      this.usedScoreAmount = Math.floor(this.usedScore / 10);

      // 更新订单的总金额
      this.calculateFinalTotal();
    },
    calculateFinalTotal() {
      const initialTotal = this.orders.orderTotal;
      this.finalTotal = initialTotal - this.usedScoreAmount;
    },
    toIndex() {
      // 检查 orderId 是否正确
      if (!this.orderId) {
        alert('订单ID不存在');
        return;
      }

      // 发起更新订单状态的请求
      this.$axios
          .post(
              "OrdersController/updateOrderState",
              {
                orderId: this.orderId,
                orderState: 1,  // 将 orderState 改为 1 表示已支付
                usedScore: this.usedScore  // 传递用户使用的积分
              },
              {
                headers: {
                  'Content-Type': 'application/json'  // 明确指定 JSON 格式
                }
              }
          )
          .then(response => {
            if (response.data.success) {
              // 支付成功后，获取用户最新积分信息
              this.$axios
                  .post('/ScoreController/getAllScore', null, {
                    params: {
                      userId: this.$route.query.userId  // 确保 userId 正确传递
                    }
                  })
                  .then(scoreResponse => {
                    this.$router.push({
                      path: '/information',  // 跳转到 Information.vue
                      query: {
                        updatedScore: scoreResponse.data  // 传递更新后的积分
                      }
                    });
                  })
                  .catch(error => {
                    console.error("获取积分失败:", error);
                  });
            } else {
              alert("支付失败，请重试");
            }
          })
          .catch(error => {
            console.error("请求失败，请稍后重试");
          });
    }
  },
  components: {
    Footer,
  },
};
</script>



<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	/****************** 订单信息部分 ******************/
	.wrapper h3 {
		margin-top: 12vw;
		box-sizing: border-box;
		padding: 4vw 4vw 0;

		font-size: 4vw;
		font-weight: 300;
		color: #999;
	}

	.wrapper .order-info {
		box-sizing: border-box;
		padding: 4vw;
		font-size: 4vw;
		color: #666;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-info p:last-child {
		color: orangered;
	}

	/****************** 订单明细部分 ******************/
	.wrapper .order-detailet {
		width: 100%;
	}

	.wrapper .order-detailet li {
		width: 100%;
		box-sizing: border-box;
		padding: 1vw 4vw;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-detailet li p {
		font-size: 3vw;
		color: #666;
	}

	/****************** 支付方式部分 ******************/
	.wrapper .payment-type {
		width: 100%;
	}

	.wrapper .payment-type li {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .payment-type li img {
		width: 33vw;
		height: 8.9vw;
	}

	.wrapper .payment-type li .fa-check-circle {
		font-size: 5vw;
		color: #38CA73;
	}

	.wrapper .payment-button {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;
	}

	.wrapper .payment-button button {
		width: 100%;
		height: 10vw;
		border: none;
		/*去掉外轮廓线*/
		outline: none;
		border-radius: 4px;
		background-color: #38CA73;
		color: #fff;
	}

  /****************** 积分部分 ******************/
  .score-section {
    margin: 20px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
  }

  .score-section p {
    font-size: 16px;
    color: #333;
  }

  .score-section input {
    width: 100%;
    padding: 8px;
    margin-top: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

  /* 样式调整 */
  .available-score {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20px;
  }

  .available-score input {
    width: 100px;
    height: 30px;
  }

</style>
